package com.develop.data.loan.manager.change.amount;

import com.develop.data.loan.manager.change.amount.api.LoanInstallmentAmountBudget;
import com.develop.data.loan.model.LoanInstallment;
import org.javamoney.moneta.Money;
import org.springframework.stereotype.Component;

import javax.money.Monetary;
import javax.money.MonetaryAmount;
import java.time.LocalDateTime;

@Component("L0001B0001LoanInstallmentPrincipalOverdueBudget")
public class L0001B0001LoanInstallmentPrincipalOverdueBudget implements LoanInstallmentAmountBudget {

    /* 已发生形态转移 */
    /* 持有时间，左受制于动帐时间，右受制于转非应计时间（不计息） */
    /* LoanInstallmentPrincipalOverdue对应Installment的PrincipalOverdue金额字段 */

    public MonetaryAmount preview(LoanInstallment loanInstallment, LocalDateTime localDate){
        return loanInstallment.getInstallmentPrincipalOverdue();
    }

    public MonetaryAmount execute(LoanInstallment loanInstallment, LocalDateTime localDate, MonetaryAmount amount){

        /* 有借必有贷 */
        /* 还款金额任意，按金额依次扣除，直到扣完 */

        MonetaryAmount amountPreviewed = this.preview(loanInstallment, localDate);

        if(amount.isGreaterThanOrEqualTo(amountPreviewed)){
            loanInstallment.setInstallmentPrincipalOverdue(loanInstallment.getInstallmentPrincipalOverdue().subtract(amountPreviewed));
            loanInstallment.setInstallmentPrincipalCleared(loanInstallment.getInstallmentPrincipalCleared().add(amountPreviewed));
            loanInstallment.setInstallmentCursor(localDate); /* 动帐时间 */
            return amount.subtract(amountPreviewed);
        };

        loanInstallment.setInstallmentPrincipalOverdue(loanInstallment.getInstallmentPrincipalOverdue().subtract(amount));
        loanInstallment.setInstallmentPrincipalCleared(loanInstallment.getInstallmentPrincipalCleared().add(amount));
        loanInstallment.setInstallmentCursor(localDate); /* 动帐时间 */
        return Money.zero(Monetary.getCurrency("CNY"));

    }

}
